package is.server.model;

import is.common.interfaces.DeactivationNeededThread;
import is.server.controller.session.remote.RemoteSessionThread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.LinkedList;

/**
 * @author aspr0
 *         Date: 26.04.12
 *         Time: 19:39
 */
public class ListeningThread extends Thread implements DeactivationNeededThread
{
    private ServerSocket serverSocket;
    private LinkedList<RemoteSessionThread> clientsSessionsList = new LinkedList<RemoteSessionThread>();
    private boolean listening = true;

    public ListeningThread(int port) throws IOException
    {
        serverSocket = new ServerSocket(port);

    }

    @Override
    public void run()
    {
        while (listening)
        {
            try
            {
                /* adding client to list */
                clientsSessionsList.add(new RemoteSessionThread(serverSocket.accept()));

                /* and starting his session */
                clientsSessionsList.getLast().start();
            }
            catch (SocketException e)
            {
                /*
                during controller deactivation after timeout is set to 0
                socket raises SocketException, breaks cycle, listening stops
                */
//                e.printStackTrace();
                break;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void deactivate() throws IOException
    {
        listening = false;

        /* socket will reach timeout immediately and listening cycle will be finished */
        serverSocket.setSoTimeout(0);
        /* while got any clients' sessions */
        while (clientsSessionsList.size() > 0)
        {
            /* removing last client from list and deactivating his session */
            clientsSessionsList.removeLast().deactivate();
        }

        serverSocket.close();
    }
}
